package com.haojiang.mh.remote.ui.dialog

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.text.method.ReplacementTransformationMethod
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.fragment.app.FragmentActivity
import com.google.zxing.Result
import com.haojiang.mh.R
import com.haojiang.mh.remote.base.BaseDialogFrag
import com.haojiang.mh.remote.enums.EConnect
import com.haojiang.mh.remote.enums.EStep
import com.haojiang.mh.remote.event.ConnectEvent
import com.haojiang.mh.remote.ui.activity.QrcodeActivity
import com.haojiang.mh.remote.utils.BleUtil
import com.haojiang.mh.remote.utils.BleUtil.Companion.readSingleSurfaceNo
import com.haojiang.mh.remote.utils.BleUtil.Companion.saveSingleSurfaceNo
import com.haojiang.mh.remote.utils.Constant.QRRM
import com.haojiang.mh.remote.utils.KeyboardUtil
import com.haojiang.mh.remote.utils.Util
import com.lx.permission.IPermissionCallback
import com.lx.permission.PermissionManager
import com.tamsiree.rxfeature.scaner.OnRxScanerListener
import kotlinx.android.synthetic.main.frag_dialog_select_control.*
import org.greenrobot.eventbus.EventBus
import java.util.*

class SelectControlDialogFrag : BaseDialogFrag() {

    /**
     * 伴生函数
     */
    companion object {
        private var BLE_ADDRESS = "ble_address"
        val instance by lazy {
            SelectControlDialogFrag()
        }

        fun show(fragmentActivity: FragmentActivity, bleAddress: String) {
            val fm = fragmentActivity.supportFragmentManager
            fm.executePendingTransactions()
            fm.beginTransaction().remove(instance)
            instance.arguments = Bundle(bundleOf(BLE_ADDRESS to bleAddress))
            instance.show(fm, SelectControlDialogFrag::class.java.simpleName)
        }
    }


    private val onClickListener = object : View.OnClickListener {
        override fun onClick(v: View?) {
            if (v != null) {
                when (v.id) {
                    R.id.tvConfirm -> {
                        val interfaceNo = etSurface.text.toString().trim()
                        if (interfaceNo.length != 4) {
                            showToast(getString(R.string.m_enter_4bit_interface_no))
                        } else {
                            searchSurface(interfaceNo)
                        }
                    }
                    R.id.ivClose -> {
                        dismiss()
                    }
                }
            }
        }
    }


    private val mIPermissionCallback = IPermissionCallback {
        QrcodeActivity.setScanerListener(onRxScanerListener)
        scanQrcode()
    }

    private var bleAddress: String? = null

    override fun onSubCreate(savedInstanceState: Bundle?) {
        setStyle(STYLE_NO_TITLE, R.style.fragment_dialog)
        bleAddress = arguments!!.getString(BLE_ADDRESS)
    }

    override fun onSubCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.frag_dialog_select_control, container, false)
    }

    override fun onSubViewCreated(view: View, savedInstanceState: Bundle?) {
        dialog!!.setCancelable(true) //是否可以点击取消
        dialog!!.setCanceledOnTouchOutside(false) //dialog外面是否可以点击

        val params = dialog!!.window!!.attributes
        val context = context
        context?.let {
            //            params.width = (Util.getScreenWidth(context) * 0.7f).toInt()
            params.width = LinearLayout.LayoutParams.WRAP_CONTENT
            params.height = LinearLayout.LayoutParams.WRAP_CONTENT
            params.gravity = Gravity.CENTER
            //高度自己定义
            dialog!!.window!!.setLayout(params.width, params.height)
        }
    }


    override fun onSubActivityCreated(savedInstanceState: Bundle?) {

        ivQrcode.setOnClickListener(View.OnClickListener {
            context?.let {
                if (!Util.checkBleStatus(it)) {
                    return@OnClickListener
                }
            }
            PermissionManager.getInstance().setIPermissionCallback(mIPermissionCallback, 0)
            PermissionManager.getInstance().requestPermission(
                context,
                arrayOf(
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.CAMERA,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
            )
        })

        tvConfirm.setOnClickListener(onClickListener)
        ivClose.setOnClickListener(onClickListener)

        etSurface.setTransformationMethod(object : ReplacementTransformationMethod() {
            override fun getOriginal(): CharArray {
                return charArrayOf(
                    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
                )
            }

            override fun getReplacement(): CharArray {
                return charArrayOf(
                    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
                )
            }
        })

        etSurface.setOnEditorActionListener(TextView.OnEditorActionListener { v, actionId, event ->
            //当actionId == XX_SEND 或者 XX_DONE时都触发
            //或者event.getKeyCode == ENTER 且 event.getAction == ACTION_DOWN时也触发
            //注意，这是一定要判断event != null。因为在某些输入法上会返回null。
            //                if (actionId == EditorInfo.IME_ACTION_SEND
            //                        || actionId == EditorInfo.IME_ACTION_DONE
            //                        || (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
            if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
                KeyboardUtil.hideKeyboard(etSurface)
                //处理事件
            }
            false
        })


        initSurfaceNo()    //设置界面编号
    }

    private fun initSurfaceNo() {
//        var interfaceNo = ""
//        if (lastGroupType == GROUP_TYPE_NONE) {
//            interfaceNo = SpUtil.getData(context, SECTION_GROUP_ID, lastBleDeviceList.get(0).bleAddress, "") as String
//
//        } else {
////            interfaceNo = SpUtil.getData(context, SECTION_GROUP_ID, groupId.toString(), "") as String
//            interfaceNo = SpUtil.getData(context, SECTION_GROUP_ID, lastGroupId.toString(), "") as String
//        }
        var surfaceNo = ""
        bleAddress?.let {
            surfaceNo = readSingleSurfaceNo(it)
        }
        if (TextUtils.isEmpty(surfaceNo)) {
            etSurface.setText(null)
        } else {
            etSurface.setText(surfaceNo)
        }
    }


    private val onRxScanerListener = object : OnRxScanerListener {
        override fun onSuccess(type: String?, result: Result?) {
            result?.let {
                val interfaceNo = result.text.trim()
                if (interfaceNo.length < 4) {
                    showToast(getString(R.string.m_interface_not_exist))
                } else {
                    searchSurface(interfaceNo)
                }
            }
        }

        override fun onFail(type: String?, message: String?) {
        }
    }

    private fun searchSurface(surfaceNo: String) {

//        val funList = SurfaceKey.keyMap.get(surfaceNo.substring(0, 4).toUpperCase(Locale.ROOT))
//        if (funList == null || surfaceNo.equals(QRRM, ignoreCase = true)) {
        if (!BleUtil.isSurfaceExist(surfaceNo) || surfaceNo.equals(QRRM, ignoreCase = true)) {
            showToast(getString(R.string.m_interface_not_exist))
            return
        } else {
//            if (groupType == GROUP_TYPE_NONE) {
//            if (lastGroupType == GROUP_TYPE_NONE) {
//                SpUtil.putData(context, SECTION_GROUP_ID, lastBleDeviceList.get(0).bleAddress, intefaceNo)
//            } else {
//                SpUtil.putData(context, SECTION_GROUP_ID, lastGroupId.toString(), intefaceNo)
//            }
//            LogUtil.e(intefaceNo)
//            lastBleRssiDevice?.let {
//                //                val readLocalInterface = BleUtil.readLocalInterface(it.bleAddress)
////                LogUtil.e("读取---" + it.bleName)
////                if (TextUtils.isEmpty(readLocalInterface) ||
////                    !readLocalInterface.equals(BleUtil.lastBleRssiDevice!!.bleName)
////                ) {
////                    BleUtil.saveLocalInterface(it.bleAddress, intefaceNo)
////                }
//                BleUtil.saveLocalInterface(it.bleAddress, intefaceNo)
////                LogUtil.e("保存---" + intefaceNo + "=====" + it.bleAddress)
//            }
//            LogUtil.e("点击了确定" + bleAddress)
            bleAddress?.let {
                saveSingleSurfaceNo(it, surfaceNo)
//                LogUtil.e(BleUtil.lastConnect.surfaceNo + "==界面编号===")
                instance.dialog!!.dismiss()
                EventBus.getDefault().post(ConnectEvent(EStep.STEP_SELECT_INTERFACE.data, EConnect.CONNECT_SINGLE.data, 0L))
            }
//            devConnects(context!!, lastBleDeviceList)   //连接蓝牙设备
//            EventBus.getDefault().post(FunctionEvent(funList))
//            val bleDeviceList = ArrayList<BleRssiDevice>()
//            lastBleDeviceList.forEach {
//                bleDeviceList.add(it)
//            }
        }
    }

    override fun initDestroy() {
    }


    private fun scanQrcode() {
        startActivity(Intent(activity, QrcodeActivity::class.java))
    }
}